package com.springboot.codeminestarter.codemine.utils;

import java.util.concurrent.atomic.AtomicInteger;

public class VersionUtil {
    private static final int MAX_VERSION = 99;
    private static String version = "1.0.0";
    private static AtomicInteger firstVersion = new AtomicInteger(1);
    private static AtomicInteger secondVersion = new AtomicInteger(0);
    private static AtomicInteger thirdVersion = new AtomicInteger(0);

    public static String getVersion() throws Exception {
        synchronized (VersionUtil.class) {
            String[] nums = version.split("\\.");
            if (!version.contains(".") || nums.length != 3) {
                throw new Exception("版本号错误: " + version);
            }
            int thirdVersion = Integer.parseInt(nums[2]);
            int secondVersion = Integer.parseInt(nums[1]);
            int firstVersion = Integer.parseInt(nums[0]);

            if (++thirdVersion > MAX_VERSION) {
                thirdVersion = 0;
                if (++secondVersion > MAX_VERSION) {
                    secondVersion = 0;
                    if (++firstVersion > MAX_VERSION) {
                        throw new Exception("版本号已达峰值！");
                    }
                }
            }
            version = firstVersion + "." + secondVersion + "." + thirdVersion;
        }
        return version;
    }

    public static String getVersionWithAtomic() throws Exception {

        if (thirdVersion.getAndIncrement() > MAX_VERSION) {
            thirdVersion.set(0);
            if (secondVersion.getAndIncrement() > MAX_VERSION) {
                secondVersion.set(0);
                if (firstVersion.getAndIncrement() > MAX_VERSION) {
                    throw new Exception("版本号已达峰值！");
                }
            }
        }
        version = firstVersion + "." + secondVersion + "." + thirdVersion;
        return version;
    }
}
